<template>
    <div>
        <el-card class="card1">
            <div class="card-header">
                <span class="examName">{{ examInfo.examName }}</span>
                <span class="examTime">{{ examRecord.examTime }}</span>
                <br>
                <div style="margin-top: 50px;">
                    <span class="logicScore">逻辑题得分: {{ examRecord.logicScore }}分</span>
                    <span class="totalScore">总分: {{ examInfo.totalScore }}分</span>
                </div>
                <el-button type="primary" class='elb' @click="dialogVisible = true">
                    查看诚信截图
                </el-button>
            </div>
        </el-card>

        <el-card shadow="always" style="margin: 20px 0;">
            <div v-for="(question, index) in formattedQuestions" :key="index">
                <div class="question-header">
                    <i class="num">{{ index + 1 }}</i>
                    <!-- 题目类型 -->
                    <span class="questionType">【{{ questionTypeOptions[question.questionType] }}】</span>
                    <!-- 题目内容 -->
                    <span class="questionContent">{{ question.questionContent }}</span>
                </div>

                <div v-if="question.questionType !== '简答题'" class="options">
                    <div v-for="(option, optIndex) in question.answer" :key="optIndex">
                        <el-card class="option-card" shadow="never" style="max-width: 480px">
                            <div class="option-content"
                                :class="{ userAnswer: isUserAnswer(question.userAnswer, optIndex) }">
                                <span class="option-text">
                                    {{ String.fromCharCode(65 + optIndex) }}.&nbsp;{{ option.answer }}
                                </span>
                                <span v-if="option.isTrue === 'true'" class="icon-wrapper">
                                    <el-icon>
                                        <SuccessFilled />
                                    </el-icon>
                                </span>
                            </div>
                        </el-card>
                    </div>
                </div>

                <div v-else>
                    <div class="subjective-answer">
                        <h3 style="font-weight: 400;">我的回答: </h3>
                        <br>
                        <p style="font-weight: 400; color: orange;">{{ question.userAnswer }}</p>
                    </div>
                    <div class="score-input">
                        <span style="font-weight: 800;">评分 ：</span>
                        <el-input-number v-model="question.userScore" :min="0" :max="question.score"
                            style="height: 40px;"></el-input-number>
                    </div>
                </div>
            </div>
        </el-card>
        <el-button type="primary" @click="submitMarking">提交阅卷</el-button>
    </div>

    <el-dialog v-model="dialogVisible" title="诚信截图" width="500" :before-close="handleClose">
        <span>无</span>
    </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, computed, onMounted, inject } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElNotification } from 'element-plus';

import {
    getExamRecordById,
    getExamInfoById,
    getQuestionById,
    setObjectQuestionScore
} from '@/api/examControl/MarkExam'
// 获取当前路由信息
const route = useRoute();
const router = useRouter();
const recordId = route.params.recordId;

// 对话框显示状态
const dialogVisible = ref(false);

// 考试记录
const examRecord = reactive({
    creditImgUrl: "",
    errorQuestionIds: "",
    examId: 0,
    examTime: "",
    logicScore: 0,
    questionIds: "",
    recordId: 0,
    totalScore: 0,
    userAnswers: "",
    userId: 0,
});

// 考试信息
const examInfo = reactive({
    examName: "",
    examDesc: "",
    type: 0,
    password: '',
    examDuration: 0,
    startTime: "",
    endTime: "",
    totalScore: 0,
    passScore: 0,
    status: 0,
    questionIds: "",
    examId: 0,
    scores: ""
});

// 考试题目列表
const questions = ref<any[]>([]);

// 题目类型和难度等级映射
const questionTypeOptions = computed(() => ({
    '1': '单选题',
    '2': '多选题',
    '3': '判断题',
    '4': '简答题',
}));

const levelOptions = computed(() => ({
    '1': '简单',
    '2': '中等',
    '3': '困难',
}));

const formattedQuestions = computed(() => {
    return questions.value.map(question => ({
        ...question,
        questionType: questionTypeOptions.value[question.questionType] || '未知类型',
        level: levelOptions.value[question.level] || '未知难度',
    }));
});

// 组件挂载时调用异步函数获取数据
onMounted(async () => {
    await fetchExamRecord();
    await fetchExamInfo();
    await fetchQuestionsDetails();
});

// 获取考试记录
async function fetchExamRecord() {
    try {
        const {data} =await getExamRecordById(recordId);
        Object.assign(examRecord, data.data);
    } catch (error) {
        console.error('获取考试记录时出错:', error);
    }
}

// 获取考试信息
async function fetchExamInfo() {
    try {
        const {data} = await getExamInfoById(examRecord.examId);
        Object.assign(examInfo, data.data);
    } catch (error) {
        console.error('获取考试信息时出错:', error);
    }
}

// 获取问题详情的函数
async function fetchQuestionsDetails() {
    const questionIds = examRecord.questionIds.split(',');
    const scores = examInfo.scores.split(',');
    const userAnswers = examRecord.userAnswers.split('-');
    for (let i = 0; i < questionIds.length; i++) {
        try {
            const  {data} = await getQuestionById(questionIds[i]);
            const question = data.data;
            question.userAnswer = userAnswers[i];
            question.score = scores[i];
            question.userScore = calculateScore(question);
            questions.value.push(question);
        } catch (error) {
            console.error('获取题目详情时出错:', error);
        }
    }
}

// 计算用户得分
function calculateScore(question: any) {
    if (question.questionType == 4) {
        return 0; // 简答题默认为0，需要手动评分
    }

    const userAnswers = question.userAnswer.split(',');
    const correctAnswers = question.answer.filter(option => option.isTrue === 'true').map((_, idx) => idx.toString());

    if (userAnswers.sort().toString() == correctAnswers.sort().toString()) {
        return question.score; // 满分
    } else {
        return 0; // 零分
    }
}

// 提交阅卷结果
async function submitMarking() {
    const totalScore = questions.value.reduce((sum, question) => sum + Number(question.userScore), 0);
    try {
        await setObjectQuestionScore(totalScore,examRecord.recordId);
        ElNotification({
            title: '阅卷',
            message: '批阅成功',
            type: 'success',
        });
    } catch (error) {
        console.error('提交阅卷时出错:', error);
    }
    router.push({ path: `/home/markManage` });
}

// 检查是否是用户的答案
function isUserAnswer(userAnswer: string, index: number) {
    return userAnswer.split(',').includes(index.toString());
}

// 关闭对话框
function handleClose(done: () => void) {
    done();
}
</script>
<style scoped>
.examName {
    margin-right: 20px;
    padding-bottom: 10px;
    display: inline-block;
    color: #160f58;
    border-bottom: 4px solid #ffd550;
    font-size: 18px;
    font-weight: 700;
    padding-bottom: 10px;
}

.examTime {
    font-size: 16px;
    color: #cbcacf;
    font-weight: 700;
}

.logicScore {
    font-weight: 800;
    font-size: 17px;
}

.totalScore {
    float: right;
    font-weight: 800;
    font-size: 17px;
}

.elb {
    margin-top: 15px;
    font-size: 12px;
}

.num {
    background-image: url("");
    display: inline-block;
    height: 37px;
    width: 37px;
    font-weight: 800;
    line-height: 30px;
    color: #fff;
    font-size: 20px;
    text-align: center;
    margin-right: 15px;
}

.questionType,
.questionContent {
    font-weight: 800;
    color: #303133;
}

.userAnswer {
    opacity: 0.5;
}

ul {
    padding: 0;
    list-style-type: none;
    margin: 0;
}

.option-card {
    margin: 15px 0;
}

.option-content {
    display: flex;
    align-items: center;
}

.option-text {
    flex: 1;
    font-size: 16px;
    font-weight: 800;
}

.icon-wrapper {
    display: flex;
    margin-left: 10px;
    color: #6592f0;
    font-size: 35px;
}

.subjective-answer {
    padding: 40px 40px;
    background: #f6f6f8;
    margin: 20px 0;
}
</style>
